import json
import time
# import common.dataBase as db
import requests


def dt(w):
    s = [
        ('&#x2789;', '0'),
        ('&#x2781;', '1'),
        ('&#x2780;', '2'),
        ('&#x2782;', '3'),
        ('&#x2786;', '4'),
        ('&#x2783;', '5'),
        ('&#x2784;', '6'),
        ('&#x2788;', '7'),
        ('&#x2787;', '8'),
        ('&#x2785;', '9'),
    ]
    nw = w.replace(',', '')
    for rs in s:
        nw = nw.replace(rs[0], rs[1])
    return nw


def get_data(url, did, name):
    headers = {
        'Content-Type': 'application/json;charset=UTF-8'
    }
    param = json.dumps({
        "userId": None,
        "exponentId": did,
        "exponentName": name,
        "timeType": 5,
        "startTime": None,
        "endTime": None,
        "pIndex": 1,
        "pSize": 1,
        "areaList": [
            "华南市场价",
            "华东市场价",
            "华东出厂价",
            "华南出厂价"
        ],
        "randomToken": "dfe0e0f3-ac74-77aa-a5e7-7b50613be9ef"
    })
    response = requests.post(url, headers=headers, data=param)
    areaPriceList = json.loads(response.text)['body']['priceHistoryList'][0]
    return areaPriceList['areaPriceList'][0]['price'], areaPriceList['createDate']


def app(idd, name):
    url = 'https://wwwapi.antsoo.com/exponentPrice/exponentPriceHistory'
    d = get_data(url, idd, name)
    print(d)
    price = dt(d[0])
    price_range = ''
    # today = time.strftime('%Y-%m-%d', time.localtime())
    today = d[1]
    insert_sql = f'INSERT INTO mat_price VALUES (null, "{name}", "{price}","{price_range}", "{today}", "{url}")'
    # db.save([insert_sql])
    print(insert_sql)


if __name__ == "__main__":
    app('14', 'PBT')
